﻿using System;
using System.IO;
using System.Linq;
using System.Windows.Documents;
using System.Windows.Documents.Serialization;

namespace RG.Common.WPF.Reporting
{
    public static class DocumentPaginator_Extension
    {
        public static Stream ToStream(this DocumentPaginator paginator, Stream StreamToWrite)
        {
            IDocumentPaginatorSource Document = paginator.Source;

            var serializerProvider = new SerializerProvider();
            SerializerDescriptor selectedPlugIn =
                serializerProvider.InstalledSerializers.FirstOrDefault(p => p.DefaultFileExtension == ".xps");
            if (selectedPlugIn == null)
                throw new ApplicationException("Не установлен сериализатор документа в XPS");

            serializerProvider
                .CreateSerializerWriter(selectedPlugIn, StreamToWrite)
                .Write(Document.DocumentPaginator, null);
            return StreamToWrite;
        }

        public static MemoryStream ToStream(this DocumentPaginator paginator)
        {
            return (MemoryStream) ToStream(paginator, new MemoryStream());
        }
    }
}
